<?php


class AnalysisrService extends TP_Service {
    private $role;
    public function __construct() {
        parent::__construct();
        $this->load->model("SModel/Search_history_model");
        $this->role = $this->getRole($_SESSION[SESS_UUID]);
    }




    /**
     * 方法名 behaviorList
     *
     * @Name 获取方法列和角色方法列
     * @Desc 搜花行为列表
     * @OpenFlag 是否开放,1开放0权限控制
     * @Author      zn
     * @Date 2021-11-15 09:30:37 星期一
     * @return      [type]                   [description]
     */
    public function behaviorList($param, $export = false) {
        if (!$export) {
            $param = array_filter($param, 'filtrfunction');
            if (!isset($param['pageNo'], $param['pageSize'])) {
                exit(retJson(ErrCode::ErrCode_10002));
            }

            $conarr['pageNo'] = $param['pageNo'];
            $conarr['pageSize'] = $param['pageSize'];
        }

        // $conarr['join']    = [["tp_customer c", 'tp_search_history.customer = c.aid'], ["tp_account a", 'c.aid = a.id']];
        $conarr['join']    = ["tp_customer c", 'tp_search_history.customer = c.aid'];
        $conarr['items']   = "tp_search_history.id id, tp_search_history.created created, search_way, word_img, initiator, season, year, region, country, sales_area, cust_name, cust_code, staff_name, extra, pids";
        $conarr['orderby'] = "created desc";
        $conarr['where']   = "1 = 1";



        // 筛选
        if (!empty($param['search_way'])) {
            $conarr['where'] .= sql_format(" AND search_way = '{0}'", $param['search_way']);
        }
        if (!empty($param['initiator'])) {
            $conarr['where'] .= sql_format(" AND initiator = '{0}'", $param['initiator']);
        }
        if (!empty($param['staff_name'])) {
            $conarr['where'] .= sql_format(" AND staff_name = '{0}'", $param['staff_name']);
        }
        if (!empty($param['cust_code'])) {
            $conarr['where'] .= sql_format(" AND cust_code = '{0}'", $param['cust_code']);
        }
        if (!empty($param['region'])) {
            $conarr['where'] .= sql_format(" AND region = '{0}'", $param['region']);
        }
        if (!empty($param['country'])) {
            $conarr['where'] .= sql_format(" AND country = '{0}'", $param['country']);
        }
        if (!empty($param['season'])) {
            $conarr['where'] .= sql_format(" AND season = '{0}'", $param['season']);
        }
        if (!empty($param['year'])) {
            $conarr['where'] .= sql_format(" AND year = '{0}'", $param['year']);
        }

        if ($export) {
            $list = $this->Search_history_model->get_list_full($conarr);
        } else {
            $list = $this->Search_history_model->get_page_list($conarr);
            foreach ($list['ret'] as &$value) {
                $value['sales_area'] = json_decode($value['sales_area'], true) ?? [];
            }
        }
        return $list;
    }




    /**
     * 方法名 behaviorExport
     *
     * @Name 搜花行为导出
     * @Desc orderExport
     * @OpenFlag 是否开放,1开放0权限控制
     * @Author      zn
     * @Date 2022-01-21 16:26:36
     * @return      [type]                   [description]
     */
    public function behaviorExport($param) {
        $searchlist = $this->behaviorList($param, true);

        // 结果的花型
        $pids = [];
        foreach ($searchlist as &$val) {
            $val['pids'] = explode(",", $val['pids']);
            $pids = array_merge($pids, $val['pids']);
        }
        $pids = array_keys(array_flip($pids));
        $patternlist = $this->patternList($pids);


        $this->load->library('ProjectService/Xlsxwriter');
        $writer = new XLSXWriter();

        if (empty($searchlist)) {
            exit(retJson(ErrCode::ErrCode_10902));
        }


        $writer->writeSheetRow('sheet1', ['搜花行为分析'], ['valign' => 'center', 'halign' => 'center', 'height' => 55, 'font' => '宋体', 'font-size' => 16, 'font-style' => 'bold']);
        $writer->markMergedCell('sheet1', $start_row = 0, $start_col = 0, $end_row = 0, $end_col = 18);
        $title = [
            '搜索时间', '搜索ID', '业务员', '客户号', '客户名', '区域', '国家', '开发季', '年份', '搜索方式', '关键字/图片',
            '花型编号', '搜索匹配度', '对应花型风格', '功能', '机型', "元素描述", "花型系列", "花型创建时间"
        ];
        $styles = ['font' => '宋体', 'font-size' => 10, 'halign' => 'center', 'border' => 'left,right,top,bottom', 'valign' => "center", 'border-style' => "thin", 'height' => 50, 'font-style' => 'bold'];
        $writer->writeSheetRow('sheet1', $title, $styles);


        // 写入内容
        unset($styles['font-style']);
        $styles['height'] = 30;
        $startRow = 0;
        $endRow = 1;

        foreach ($searchlist as $v) {
            foreach ($v['pids'] as $item) {

                $items = [
                    $v['created'], $v['initiator'], $v['staff_name'], $v['cust_code'], $v['cust_name'],$v['region'], $v['country'], $v['season'],
                    $v['year'], $v['search_way'], $v['word_img'], $patternlist[$item]['no'] ?? "", $patternlist[$item]['no'] ?? "", $patternlist[$item]['style'] ?? "",
                    $patternlist[$item]['function'] ?? "", $patternlist[$item]['model'] ?? "",
                    $patternlist[$item]['element'] ?? "", $patternlist[$item]['series'] ?? "", $patternlist[$item]['created'] ?? ""
                ];
                $writer->writeSheetRow('sheet1', $items, $styles);
            }

            // foreach ($pids as $val) {
                // $item = [
                //     // $v['id'], $v['initiator'], $v['staff_name'], $v['cust_code'], $v['cust_name'],$v['region'], $v['country'], $v['areas'],
                //     $v['id'], $v['initiator'], $v['staff_name'], $v['cust_code'], $v['cust_name'],$v['region'], $v['country'], "543453",
                //     $v['season'], $v['year'], $v['search_way'], $v['word_img'], $patternlist[$val]['no'], $patternlist[$val]['no'],
                //     $patternlist[$val]['style'], $patternlist[$val]['function'], $patternlist[$val]['model'], $patternlist[$val]['element'],
                //     $patternlist[$val]['series'], $patternlist[$val]['created']
                // ];
                // $writer->writeSheetRow('sheet1', $item, $styles);
            // }




            // $startRow = $endRow + 1;
            // $endRow = $startRow + count($v['pids']) - 1;
            // // 上下合并0到9单元格
            // for ($i = 0; $i <= 9; $i++) {
            //     $writer->markMergedCell('sheet1', $start_row = $startRow, $start_col = $i, $end_row = $endRow, $end_col = $i);
            // }
        }

        $path = 'export/behavior/';
        if (!file_exists($path)) {
            mkdir($path, 0777);
        }
        $file = $path . time() . '.xlsx';
        $writer->writeToFile($file);
        return array('path' => $file);
    }






    /**
     * 方法名 patternList
     *
     * @Name patternList
     * @Desc 行为结果

     * @OpenFlag 是否开放,1开放0权限控制
     * @Author      DJC
     * @Date 2022-02-25 17:44:34
     * @return      [type]                   [description]
     */
    public function patternList($pids) {

        if(empty($pids)){
            return [];
        }
        $pids = array_filter($pids, 'filtrfunction');
        //去重;
        // $arr = array_flip(array_flip(explode(',', $pids)));
        $pid = implode(",", $pids);

        $sql = "SELECT
        tp_pattern.*,
        group_concat(
            pp.property_key
            ORDER BY
                `pp`.`property_key` ASC SEPARATOR ','
        ) AS `property_key`,
        group_concat(
            pp.property_value
            ORDER BY
                `pp`.`property_key` ASC SEPARATOR '|'
        ) AS `property_value`
    FROM
        tp_pattern
    LEFT JOIN tp_pattern_property AS pp ON pp.pid = tp_pattern.pid";

    if(!empty($pid)){
        $sql .= " WHERE tp_pattern.pid in ({$pid})";
    } else {
		$sql .= " WHERE tp_pattern.pid=-1";
	}

    $sql .= " GROUP BY pp.pid";




        $ret = $this->Search_history_model->query($sql);

        $arr  = [];
        foreach ($ret as &$value) {
            $json = explode("|",$value['property_value']);
            $pkey = explode(",",$value['property_key']);
            foreach ($pkey as $key => $v1) {
                $value[$v1] = json_decode($json[$key],true)['value'];
                if (is_array($value[$v1])) {
                    $value[$v1] = implode(",", $value[$v1]);
                }
            }
            $arr[$value['pid']] = $value;
        }
        return $arr;
    }
}
